﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Keepo.Models;
using Keepo.Models.Services;
using System.IO;
using AlbumDesigner.Helpers;

namespace AlbumDesigner.Controllers
{
    public class AlbumImagesController : Controller
    {
        private AlbumContext db = new AlbumContext();

        public ActionResult Index(int AlbumId)
        {
            //redirect the user if he has no permission for this album
            if (!AlbumsLogic.canUserEdit(AlbumId))
            {
                return View("NoPermission");
            }

            ViewBag.AlbumId = AlbumId;
            ViewBag.AlbumTitle = db.Albums.Find(AlbumId).Title;

            return View();
        }

        [HttpPost]
        public ActionResult GetImagesList(int AlbumId, int? AlbumSectionId, int Page = 1)
        {
            //get all the images of the specified Album (or Section)
            var imagesList = db.AlbumImages.Where(i => i.AlbumId == AlbumId && !i.IsRemoved);
            if (AlbumSectionId != null)
            {
                imagesList = imagesList.Where(m => m.AlbumSectionId == AlbumSectionId);
            }
            else
            {
                imagesList = imagesList.Where(m => m.AlbumSectionId == null);
            }

            var images = imagesList.ToList().Select(m => new
            {
                DesignImageId = m.DesignImageId,
                Title = m.Title,
                ThumbnailUrl = m.ThumbnailUrl,
                IsInUse = IsImageInUse(AlbumId, m.DesignImageId)
            }).ToList();

            //add the Paging settings to the images list
            int rowsPerPage = 12;
            int imagesCount = images.Count();
            int startIndex = (Page - 1) * rowsPerPage;
            int pagesCount = imagesCount / rowsPerPage;
            if (imagesCount % rowsPerPage > 0)
            {
                pagesCount++;
            }

            var imagesPages = images.Skip(startIndex).Take(rowsPerPage);

            return Json(new { Images = imagesPages, Pages = pagesCount });
        }

        [HttpPost]
        public ActionResult GetCategoriesList(int AlbumId)
        {
            var albumTitle = db.Albums.Find(AlbumId).Title;
            var sections = db.AlbumSections.Where(m => m.AlbumId == AlbumId).ToList();

            //get list of sections of this album
            var categoriesList = sections.Select(m => new
            {
                CategoryId = m.AlbumSectionId,
                Title = m.Title,
                ItemsCount = db.AlbumImages.Count(n => n.AlbumSectionId == m.AlbumSectionId && n.IsRemoved == false)
            }).ToList();

            //add the album itself
            categoriesList.Insert(0, new
            {
                CategoryId = 0,
                Title = albumTitle,
                ItemsCount = db.AlbumImages.Count(n => n.AlbumId == AlbumId && n.AlbumSectionId == null && n.IsRemoved == false)
            });

            return Json(categoriesList);
        }

        [HttpPost]
        public ActionResult DeleteAlbumImage(string imagesIds)
        {

            var images = imagesIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            var imageIds = new List<long>();
            images.ToList().ForEach(m => imageIds.Add(long.Parse(m)));
            DeleteAlbumImage(imageIds.ToArray());

            return Json(new KeyValuePair<bool, string>(true, "התמונה נמחקה בהצלחה."));
        }

        [HttpPost]
        public ActionResult DeleteAlbumImages(long[] imageIds)
        {
            DeleteAlbumImage(imageIds);
            return Json(true);
        }

        public ActionResult DownloadAlbumImage(long imageId)
        {
            var image = db.AlbumImages.Find(imageId);
            if (image != null)
            {
                var filename = Server.MapPath("~/" + image.URL);
                var contentType = FilesHelper.GetContentType(filename);

                return File(filename, contentType, Path.GetFileName(filename));
            }

            return Json(null, JsonRequestBehavior.AllowGet);
        }

        public void DeleteAlbumImage(long[] imageIds)
        {
            //loop through all the specified images
            foreach (var imageId in imageIds)
            {
                //find the AlbumImage and delete it
                var albumImage = db.AlbumImages.Find(imageId);

                if (AlbumsLogic.canUserEdit(albumImage.AlbumId.Value))
                {
                    //check that this image is not in use
                    if (!IsImageInUse(albumImage.AlbumId.Value, albumImage.DesignImageId))
                    {
                        //AlbumHelper.DeleteAlbumImageFiles(albumImage);

                        albumImage.IsRemoved = true;
                        db.SaveChanges();
                    }
                }
            }
        }

        public ActionResult UpdateAlbumImage(int id)
        {
            var image = db.AlbumImages.Find(id);

            ViewBag.DesignImageId = image.DesignImageId;
            ViewBag.Title = image.Title;

            return PartialView();
        }

        [HttpPost]
        public ActionResult UpdateAlbumImage(int DesignImageId, string Title)
        {
            //find the specified image and update its details
            var existImage = db.AlbumImages.Find(DesignImageId);

            existImage.Title = Title;

            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "התמונה עודכנה בהצלחה."));
        }

        [HttpPost]
        public ActionResult MoveImagesToSection(string imagesIds, int? categoryId)
        {
            var images = imagesIds.Split(',');

            //loop through all the specified images
            foreach (var imageId in images)
            {
                if (!string.IsNullOrEmpty(imageId))
                {
                    //find the AlbumImage and update its Section
                    var albumImage = db.AlbumImages.Find(int.Parse(imageId));
                    albumImage.AlbumSectionId = categoryId;
                }
            }

            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "התמונה הועברה בהצלחה."));
        }

        private bool IsImageInUse(int AlbumId, long DesignImageId)
        {
            var isInUse = db.ImagePagePairs.Any(n => n.AlbumPage.AlbumSection.AlbumId == AlbumId && n.AlbumImageId == DesignImageId);
            return isInUse;
        }

        // Flex
        public ActionResult GetGeneralImages()
        {
            return Json(AlbumsLogic.getGeneralImages(), JsonRequestBehavior.AllowGet);
        }

        // Flex
        [HttpPost]
        public ActionResult GetImagesByAlbumId(int albumId)
        {
            return Json(AlbumsLogic.getImagesByAlbumId(albumId));
        }

        // Flex
        [HttpPost]
        public ActionResult GetImagesBySectionId(int sectionId)
        {
            return Json(AlbumsLogic.getImagesBySectionId(sectionId));
        }

        // Flex
        [HttpPost]
        public ActionResult GetAlbumImagesCategories(int albumId, int sectionId)
        {
            return Json(AlbumsLogic.getAlbumSectionNames(albumId, sectionId));
        }

        // Flex
        [HttpPost]
        public ActionResult GetImageIdsInAlbumExceptPage(int pageId)
        {
            return Json(AlbumsLogic.getImagePagePairs(pageId));
        }
    }
}